import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/utils/comm_utils.dart';
import 'package:qr_utils/qr_utils.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart';

class QrCodePage extends StatefulWidget {
  final User user;
  final sellerNum;

  const QrCodePage(this.user, this.sellerNum);

  @override
  _QrCodePageState createState() => _QrCodePageState();
}

class _QrCodePageState extends State<QrCodePage> {
  Image image;
  GlobalKey rootWidgetKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    _initData();
  }

  void _initData() async {
    Image tmp = await QrUtils.generateQR(widget.user.userId);
    setState(() {
      image = tmp;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0XFF3F3F3F),
      appBar: AppBar(
        elevation: 0.0,
        titleSpacing: 0,
        backgroundColor: Color(0XFF3F3F3F),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          "我的名片",
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
          ),
        ),
        actions: <Widget>[
          FlatButton(
            onPressed: () async {
              Uint8List image = await _capturePng();
              _share(image);
            },
            child: Text(
              "分享",
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
              ),
            ),
          )
        ],
      ),
      body: RepaintBoundary(
        key: rootWidgetKey,
        child: Stack(
          children: <Widget>[
            Align(alignment: Alignment.center, child: _qrBgWidget()),
            Align(alignment: Alignment.topCenter, child: _contentWidget()),
          ],
        ),
      ),
    );
  }

  ///背景
  Widget _qrBgWidget() {
    return Container(
      width: Comm.screenWidth - 40,
      height: Comm.screenHeight * 2 / 3,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
    );
  }

  ///名片内容
  Widget _contentWidget() {
    return Container(
      margin: EdgeInsets.only(bottom: Comm.screenHeight / 6 - 36),
      padding: EdgeInsets.only(bottom: 10),
      child: Column(
        children: <Widget>[
          _imgUrlWidget(),
          _nameWidget(),
          _indruceWidget(),
          _dividerWidget(),
          Expanded(child: _qrCodeWidget(), flex: 1),
          _scanHintWidget(),
        ],
      ),
    );
  }

  ///用户头像
  Widget _imgUrlWidget() {
    return Container(
      width: 72,
      height: 72,
      margin: EdgeInsets.only(top: 28),
      child: ClipOval(
          child: CachedNetworkImage(
        imageUrl: Api.getUrl(null != widget.user ? widget.user.imgUrl : ""),
        fit: BoxFit.cover,
        errorWidget: (context, url, error) =>
            Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
      )),
      decoration: BoxDecoration(
        color: Theme.of(context).accentColor,
        border: Border.all(color: Colors.white, width: 2),
        borderRadius: BorderRadius.circular(36),
      ),
    );
  }

  ///用户昵称
  Widget _nameWidget() {
    return Container(
      child: Text(
        widget.user.userName ?? "",
        style: TextStyle(
          fontSize: 22,
          fontWeight: FontWeight.w400,
        ),
      ),
      padding: EdgeInsets.only(top: 6),
    );
  }

  ///介绍信息
  Widget _indruceWidget() {
    String indruce = "";
    if (null != widget.user.birth) {
      if (widget.user.birth.startsWith("198")) {
        indruce += "80后";
      } else if (widget.user.birth.startsWith("199")) {
        indruce += "90后";
      } else if (widget.user.birth.startsWith("20")) {
        indruce += "00后";
      }
    }
    // ignore: null_aware_in_condition
    if (null != widget.user.sex) {
      indruce += "${widget.user.sex}生，";
    }
    if (null == widget.user.createAt) {
      indruce += "加入单片机助手1天,卖出${widget.sellerNum}件商品";
    } else {
      indruce +=
          "加入单片机助手${CommUtil.subDate(widget.user.createAt)}天,卖出${widget.sellerNum}件商品";
    }
    return Container(
      constraints: BoxConstraints(maxWidth: Comm.screenWidth - 80),
      child: Text(
        indruce,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: Colors.grey,
          fontSize: 16,
        ),
      ),
      padding: EdgeInsets.only(top: 10, bottom: 10),
    );
  }

  ///分割线
  Widget _dividerWidget() {
    return Container(
      height: 1,
      margin: EdgeInsets.only(left: 40, right: 40, top: 10),
      color: Color(0xfff2f2f2),
    );
  }

  ///二维码展示
  Widget _qrCodeWidget() {
    return Container(
      width: Comm.screenHeight * 2 / 3 - 132,
      height: Comm.screenHeight * 2 / 3 - 132,
      child: image,
    );
  }

  ///扫码提示
  Widget _scanHintWidget() {
    return Text(
      "扫描二维码，关注我吧",
      style: TextStyle(color: Colors.grey, fontSize: 18),
    );
  }

  Future<Uint8List> _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
          rootWidgetKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      return pngBytes; //这个对象就是图片数据
    } catch (e) {
      print(e);
    }
    return null;
  }

  void _share(Uint8List image) async {
    File file =
        await CommUtil.saveFile(image, fileName: "My_business_card.png");
    print("保存文件目录：$file");
    SSDKMap params = SSDKMap()
      ..setGeneral(
        null,
        null,
        [file.path],
        null,
        file.path,
        null,
        null,
        null,
        null,
        null,
        SSDKContentTypes.file,
      );

    SharesdkPlugin.showMenu(
        null,
        params,
        (SSDKResponseState state, ShareSDKPlatform platform, Map userData,
            Map contentEntity, SSDKError error) {});
  }
}
